#include "pthreadpool.h"
int exitpipefd[2];
void handler(int signum)
{
    printf("signal=%d\n",signum);
    write(exitpipefd[1],"1",1);
}
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,5);
    share_t share;
    pipe(exitpipefd);
    if(fork())
    {
        close(exitpipefd[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("父进程正在准备退出\n");
        exit(0);
    }
    close(exitpipefd[1]);
    pthreadshare_init(&share,atoi(argv[3]),argv[4]);
    int sockfd=initTcp(argv[1],argv[2]);
    int epfd=epoll_create(1);
    epolladd(epfd,sockfd);
    epolladd(epfd,exitpipefd[0]);
    makeworker(&share);
    struct epoll_event readyset[1024];
    while(1)
    {
        int ret = epoll_wait(epfd,readyset,1024,-1);
        for(int i=0;i<ret;i++)
        {
            if(readyset[i].data.fd==sockfd)
            {
                int netfd = accept(sockfd,NULL,NULL);
                printf("one client has conected,netd=%d\n",netfd);
                pthread_mutex_lock(&share.mutex);
                printf("主线程获得了netfd %d\n",netfd);
                enqueue(&share.queue,netfd);
                pthread_cond_broadcast(&share.cond);
                pthread_mutex_unlock(&share.mutex);
            }
            else if(readyset[i].data.fd==exitpipefd[0])
            {
                printf("线程池正在准备退出\n");
                pthread_mutex_lock(&share.mutex);
                share.exitflag = 1;
                pthread_cond_broadcast(&share.cond);
                pthread_mutex_unlock(&share.mutex);
                for(int j=0;j<share.ptidarr.workernum;j++)
                {
                    pthread_join(share.ptidarr.tidarr[j],NULL);
                }
                printf("主线程正在退出\n");
                exit(0);
            }
        }
    }
}

